<?php
namespace app\common\service;

use app\common\model\UserPermission as UserPermissionModel;
use app\common\validate\UserPermissionValidate;


class UserPermission{

    public function getPermissions(){

        $userPermissionModel = new UserPermissionModel();
        $userPermissions = $userPermissionModel->order('id asc')->paginate(20);

        return $userPermissions;
    }

    public function insert($data){
        $permissionModel = new UserPermissionModel();

        $result = $permissionModel->validate('UserPermissionValidate.add')->save($data);

        if(false === $result){
            return ['state'=>0,'message'=>$permissionModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$permissionModel->id];
    }

    public function update($data){
        $permissionModel = new UserPermissionModel();

        if(intval($data['id']) <1){
            return ['state'=>0,'message'=>"参数错误"];
        }

        $result = $permissionModel->validate('UserPermissionValidate.edit')->save($data,['id'=>intval($data['id'])]);

        if(false === $result){
            return ['state'=>0,'message'=>$permissionModel->getError()];
        }

        return ['state'=>1,'message'=>'','insertId'=>$permissionModel->id];
    }

    public function delete($ids){
        $permissionModel = new UserPermissionModel();

        $count = $permissionModel ->destroy($ids);

        return $count;
    }

    public function find($id){

        $permissionModel = new UserPermissionModel();

        return $permissionModel -> get($id);
    }


    /**
     * 按照group分好组 返回
     * @return array
     */
    public function getAllPermissions(){

        $permissionModel = new UserPermissionModel();
        $permissions = $permissionModel->all();
        $permissions = collection($permissions)->toArray();

        $group = array_column($permissions,"group");
        $group = array_unique($group);

        $lists = [];
        foreach( $permissions as $key => $val ){
            if(!isset($lists[$val['group']])){
                $lists[$val['group']] = [];
            }
            array_push($lists[$val['group']],$val);
        }

        return $lists;
    }
}